//
//  SAWHomeWorkWebVC.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/29.
//  Copyright © 2018年 星道三好. All rights reserved.
//
#import <WebKit/WebKit.h>
#import "HMWorkSelectCourseVC.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "SAWHomeWorkWebVC.h"

@interface SAWHomeWorkWebVC ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property(nonatomic,strong)WKWebView *webview;

@property(nonatomic,copy)NSString * url;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) WKUserContentController *userContent;
@end

@implementation SAWHomeWorkWebVC
- (void)itemAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
  self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(itemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    self.navigationItem.title=@"已选题目";
    UIButton *releaseButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [releaseButton setTitle:@"编辑" forState:UIControlStateNormal];
    [releaseButton setTitle:@"取消" forState:UIControlStateSelected];
    [releaseButton addTarget:self action:@selector(changeWebStu:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *releaseButtonItem = [[UIBarButtonItem alloc] initWithCustomView:releaseButton];
    self.navigationItem.rightBarButtonItem = releaseButtonItem;
    
    
    _url =[NSString stringWithFormat:@"assignHomework.do?action=knowpointlist&homewordId=%@&type=0",self.homeworkID];
    
    
    [self setUI];
}

-(void)setCookie
{
    

    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];

        NSString *appendString = [NSString stringWithFormat:@"uid=%@;",[AccountTool shareAccountTool].currentAccount.authCode];

        [cookieValue appendString:appendString];

     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:LLBaseURL(_url)]];
    [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [_webview loadRequest:request];
}
-(void)setUI
{
    
    WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc]init];
    config.preferences = [WKPreferences new];
    config.preferences.javaScriptEnabled=YES;
    
    _userContent = [[WKUserContentController alloc]init];
    [_userContent addScriptMessageHandler:self name:@"getLessonList"];
    
    config.userContentController = _userContent;
    
    _webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kTopHeight) configuration:config];
    [self.view addSubview:_webview];
    _webview.UIDelegate=self;
    _webview.navigationDelegate=self;
    [_webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    [self setCookie];
    
   
}
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    //  js 里面的alert实现，如果不实现，网页的alert函数无效  ,
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil
                preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault
            handler:^(UIAlertAction *action) {
                        completionHandler();}]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                style:UIAlertActionStyleCancel
            handler:^(UIAlertAction *action){
        completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {

    //  js 里面的alert实现，如果不实现，网页的alert函数无效  ,
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil
                preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault
        handler:^(UIAlertAction *action) {
    completionHandler(YES);}]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
        style:UIAlertActionStyleCancel
            handler:^(UIAlertAction *action){
            completionHandler(NO);
                                                      }]];

    [self presentViewController:alertController animated:YES completion:^{}];

}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
}
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@".......%@",message.body);
    if ([message.name isEqualToString:@"getLessonList"]) {
        
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[HMWorkSelectCourseVC class]]) {
                HMWorkSelectCourseVC *revise =(HMWorkSelectCourseVC *)controller;
                [self.navigationController popToViewController:revise animated:YES];
            }
        }
        
    }
    
    
}
#pragma mark 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webview && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1)
        {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

- (UIProgressView *)progressView
{
    if (!_progressView)
    {
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
        progressView.tintColor = self.navigationController.navigationBar.tintColor;
        progressView.trackTintColor = [UIColor whiteColor];
        [self.view addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}

#pragma mark - 监听记得移除 不然会造成崩溃
- (void)dealloc {
    [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
    [_userContent removeScriptMessageHandlerForName:@"getLessonList"];
}

-(void)changeWebStu:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        _url = [NSString stringWithFormat:@"assignHomework.do?action=knowpointlist&homewordId=%@&type=1",self.homeworkID];
        [self setCookie];
    }
    else
    {
        _url = [NSString stringWithFormat:@"assignHomework.do?action=knowpointlist&homewordId=%@&type=0",self.homeworkID];
        [self setCookie];
    }
 
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
